package com.linzi.common.utils;

import com.linzi.common.enums.CompareEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * @Author Administrator
 * @Date 2023/7/21 16:12
 * @Version 1.0
 * @Description 运行js 工具类
 */
@Slf4j
public class ScriptUtils {
    /**
     * 计算公式
     *
     * @param standard 公式
     * @param val      值
     * @return
     */
    public static Boolean compareFormula(String standard, String val) {
        if (StringUtils.isBlank(standard) || StringUtils.isBlank(val)) {
            return false;
        }
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            engine.put("val", val);
            return (Boolean) engine.eval(standard);
        } catch (Exception e) {
            log.info("js计算公式失败,失败信息：" + e.getMessage());
            return false;
        }
    }


    /**
     * 组装公式
     *
     * @param oneType  指标1  类型
     * @param oneValue 指标1  值
     * @param twoType  指标2  类型
     * @param twoValue 指标2  值
     * @return
     */
    public static String makeFormula(Integer oneType, Long oneValue, Integer twoType, Long twoValue) {
        StringBuilder formula = new StringBuilder();
        if (oneType != null && oneValue != null) {
            CompareEnum oneCompare = CompareEnum.selectByCode(oneType);// 指标1  比较符号
            formula.append(CompareEnum.VAL.getName()).append(oneCompare.getName()).append(oneValue);
        }
        /**指标2 的类型和值不为空才去拼接*/
        if (twoType != null && twoValue != null) {
            CompareEnum twoCompare = CompareEnum.selectByCode(twoType);// 指标2  比较符号
            formula.append(CompareEnum.AND.getName());
            formula.append(CompareEnum.VAL.getName()).append(twoCompare.getName()).append(twoValue);
        }
        return formula.toString();
    }
}
